package com.ruoyi.system.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.ruoyi.system.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {

    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.privateKey}")
    private String privateKey;

    @Value("${alipay.publicKey}")
    private String publicKey;

    @Value("${alipay.gateway}")
    private String gateway;

    private AlipayClient alipayClient;

    private AlipayClient getAlipayClient() {
        if (alipayClient == null) {
            alipayClient = new DefaultAlipayClient(gateway, appId, privateKey, "json", "UTF-8", publicKey, "RSA2");
        }
        return alipayClient;
    }

    @Override
    public String createH5Pay(String subject, String orderNo, int amount, String ip, String notifyUrl) {
        try {
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            // 设置异步通知地址
            request.setNotifyUrl(notifyUrl);
            
            // 构建请求参数
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("subject", subject);
            bizContent.put("out_trade_no", orderNo);
            // 将分转换为元
            BigDecimal totalAmount = new BigDecimal(amount).divide(new BigDecimal(100));
            bizContent.put("total_amount", totalAmount.toString());
            bizContent.put("product_code", "QUICK_WAP_WAY");
            
            request.setBizContent(com.alibaba.fastjson.JSON.toJSONString(bizContent));
            
            // 调用SDK生成表单
            String form = getAlipayClient().pageExecute(request).getBody();
            log.info("支付宝支付表单：{}", form);
            return form;
            
        } catch (AlipayApiException e) {
            log.error("创建支付宝支付失败", e);
            return null;
        }
    }

    @Override
    public boolean verifyNotify(Map<String, String> params) {
        try {
            // 1. 验证通知数据中是否包含必要的参数
            String tradeStatus = params.get("trade_status");
            if (tradeStatus == null) {
                log.error("支付宝异步通知参数不完整");
                return false;
            }

            // 2. 使用支付宝SDK验证签名
            boolean signVerified = com.alipay.api.internal.util.AlipaySignature.rsaCheckV1(
                    params,
                    publicKey,
                    "UTF-8",
                    "RSA2"
            );

            // 3. 验证交易状态
            if (signVerified) {
                // TRADE_SUCCESS 表示交易成功
                return "TRADE_SUCCESS".equals(tradeStatus);
            }

            log.error("支付宝异步通知验签失败");
            return false;
        } catch (AlipayApiException e) {
            log.error("支付宝异步通知验证异常", e);
            return false;
        }
    }
} 